package net.airtheva.uniqueTask2;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WriteTweetActivity extends Activity {

	public static final int REQUEST_CODE_ADD_IMAGE = 0;
	
	String mSession = null;
	
	EditText mContent = null;
	Button mAddImage = null;
	Button mSubmit = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mSession = getIntent().getStringExtra("session");
		
		setContentView(R.layout.fragment_write_tweet);

		mContent = (EditText) findViewById(R.id.fragment_write_tweet_content);
		mAddImage = (Button) findViewById(R.id.fragment_write_tweet_addImage);
		mAddImage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				WriteTweetActivity.this.startActivityForResult(intent, REQUEST_CODE_ADD_IMAGE);

			}
		});
		
		
		mSubmit = (Button) findViewById(R.id.fragment_write_tweet_submit);
		mSubmit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Submit(Translator.Convert(mContent.getText()));
			}
		});
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		if(resultCode == RESULT_OK) {
			
			switch(requestCode) {
			case REQUEST_CODE_ADD_IMAGE:
				Uri uri = data.getData();
				ImageSpan is = new ImageSpan(this, uri, ImageSpan.ALIGN_BASELINE);
				Editable content = mContent.getEditableText();
				content.append("[image]");
				content.setSpan(is, content.length() - 7, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				break;
			}
			
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void Submit(String content) {
		
		Response res = API.GetInstance(this).WriteTweet(mSession, content);
		switch(res.GetStatusCode()) {
		case Response.STATUS_CODE_SUCCESS:
			Toast.makeText(this, "提交成功！", Toast.LENGTH_SHORT).show();
			break;
		default:
			Toast.makeText(this, res.GetExtra(), Toast.LENGTH_SHORT).show();
			break;
		}
		finish();
	}
	
}
